package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 调用微信接口服务，获取微信用户openid的方法
     * 微信auth.code2Session 接口说明：
     * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
     * @param code
     * @return
     */
    public String getOpenid(String code) {
        //设置请求参数
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        //向微信服务接口发送get请求，将响应回的数据转为字符串
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        //重新将字符串转为json对象
        JSONObject jsonObject = JSON.parseObject(json);
        //获取openid
        String openid = jsonObject.getString("openid");
        return openid;
    }

    /**
     * 微信用户登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //获取微信用户的openid
        String openid = getOpenid(userLoginDTO.getCode());
        //如果未获取到openid，表示登录失败，抛登录失败异常
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //获取到openid后，从数据库中查询当前用户
        User user = userMapper.getByOpenId(openid);
        //若为新用户，则注册
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            //向数据库插入数据，需要返回主键id
            userMapper.insert(user);
        }
        return user;
    }
}
